// 从 vue-router 中导入所需的具名导出
import { createRouter, createWebHistory } from 'vue-router';

// 创建路由实例
const minBangRouter = createRouter({
  // 使用 HTML5 历史模式
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "home",
      component: () => import("./views/Home.vue"),
    },
    {
      path: "/news",
      name: "news",
      component: () => import("./views/News.vue"),
    },
    {
      path: "/newsDetails/:id",
      name: "newsDetails",
      component: () => import("./views/NewsDetails.vue"),
    },
    {
      path: "/case",
      name: "case",
      component: () => import("./views/Case.vue"),
    },
    {
      path: "/caseDetails/:id",
      name: "caseDetails",
      component: () => import("./views/CaseDetails.vue"),
    },
    {
      path: "/goIn",
      name: "goIn",
      component: () => import("./views/GoIn.vue"),
    },
    {
      path: "/login",
      name: "login",
      component: () => import("./views/Login.vue"),
    },
    {
      path: "/admin",
      name: "admin",
      meta: {
        requireAuth: true,
      },
      component: () => import("./views/Admin.vue"),
      children: [
        {
          path: "user", // 注意：Vue 3 中子路由路径不需要加父路径前缀
          name: "user",
          component: () => import("./views/Admin/User.vue"),
        },
        {
          path: "news",
          name: "new",
          component: () => import("./views/Admin/News.vue"),
        },
        {
          path: "cases",
          name: "cases",
          component: () => import("./views/Admin/Cases.vue"),
        },
        {
          path: "team",
          name: "team",
          component: () => import("./views/Admin/Team.vue"),
        },
        {
          path: "course",
          name: "course",
          component: () => import("./views/Admin/Course.vue"),
        },
        {
          path: "enterprise",
          name: "enterprise",
          component: () => import("./views/Admin/Enterprise.vue"),
        },
        {
          path: "honor",
          name: "honor",
          component: () => import("./views/Admin/Honor.vue"),
        },
      ],
    },
  ],
});

// 判断是否需要登录权限 以及是否登录
minBangRouter.beforeEach((to, from, next) => {
  // 在路由切换后滚动到页面顶部
  window.scrollTo(0, 0);
  // 判断是否需要登录权限
  if (to.matched.some((res) => res.meta.requireAuth)) {
    // 判断是否登录
    if (sessionStorage.getItem("token")) {
      next();
    } else {
      // 没登录则跳转到登录界面
      next({
        path: "/login",
        query: {
          redirect: to.fullPath,
        },
      });
    }
  } else {
    next();
  }
});

export default minBangRouter;